package com.itheima.controller;

import com.alibaba.fastjson2.JSON;
import com.itheima.common.Code;
import com.itheima.common.Result;
import com.itheima.common.ThreadLocalUtil;
import com.itheima.dto.ShoppingCarDto;
import com.itheima.dto.UserlogInDto;
import com.itheima.service.ShoppingCarService;
import com.itheima.vo.ShoppingCarVo;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author :WuJunJie
 * packageName :com.itheima.controller
 * fileName :ShopingCarController
 * creationTime :2022-11-27 11:15
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCarController {
    @Autowired
    private ShoppingCarService shoppingCarService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("add")
    public Result insertShoppingCar(@RequestBody ShoppingCarDto shoppingCarDto, HttpServletRequest request){
        Boolean unlocked = redisTemplate.opsForValue().setIfAbsent(ThreadLocalUtil.getid(), JSON.toJSONString(shoppingCarDto), 200, TimeUnit.MILLISECONDS);
        if (!unlocked){
            return Result.error("你操作的太快了，慢点！");
        }
        ShoppingCarVo shoppingCarVo =shoppingCarService.insertShoppingCar(shoppingCarDto);
        return Result.success(shoppingCarVo);
    }

    @DeleteMapping("clean")
    public Result deleteAllShoppingCar(HttpServletRequest request){

        Boolean delete=shoppingCarService.deleteAllShoppingCar();
        if (delete){
            return Result.success();
        }
        return Result.error(Code.Forbidden.getCode());
    }
    @PostMapping("sub")
    public Result deleteShoppingCar(@RequestBody ShoppingCarDto shoppingCarDto){

        ShoppingCarVo delete=shoppingCarService.deleteShoppingCar(shoppingCarDto);
        if (delete!=null){
            return Result.success(delete);
        }

        return Result.error(Code.Forbidden.getCode());
    }
//    @Cacheable(value = "shoppingCar")
//    @CacheEvict
    @GetMapping("list")
    public Result selectShoppingCar(){

        List<ShoppingCarVo> shoppingCars=shoppingCarService.selectShoppingCar();
        return Result.success(shoppingCars);
    }
}
